<script setup lang="ts">
import { getAddressByIdApi, postAddressApi, putAddressApi } from '@/api/address'
import { onShowRefreshData } from '@/utils/common'
import { useAddressStore } from '@/stores/modules/address'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getAreaDataApi, getGoogleMap, getMapInfo } from '@/api/common'
import { countries, stateOptions } from '@/static/country/country.ts';
import { useMemberStore } from '@/stores'
import { debounce } from 'lodash'
import PhoneNumberInput from '@/components/phone-number-input/phone-number-input.vue'
const memberStore = useMemberStore()

// 表单数据
const form = ref<any>({
  first_name: '',
  last_name: '',
  name: '',
  phone: '',
  province: '',
  city: '',
  address: '',
  zipcode: '',
  county: 'United States',
  is_default: 0,
  full_location: ''
})
let phoneCode = ref('+1')
const localAreaData = ref()
const stateData = ref<any[]>([])

//获取参数
const query = defineProps<{
  id?: string
}>()

//获取地址详情
const getAddressDetail = async () => {
  if (query.id) {
    const res = await getAddressByIdApi(query.id)

    if (res.result) {

      const addressDetail = res.result;

      // Map API response to our form fields
      // 解析电话号码
      let phoneNumber = '';
      let countryCode = '+1';
      if (addressDetail.phone) {
        // 假设电话号码格式为 +xx xxxxxxxxxx
        const phoneMatch = addressDetail.phone.match(/^(\+\d+)\s*(.*)$/);
        if (phoneMatch) {
          countryCode = phoneMatch[1];
          phoneNumber = phoneMatch[2];
        } else {
          phoneNumber = addressDetail.phone;
        }
        phoneCode.value = countryCode;
      }


      // Split name into first and last name if needed
      const nameParts = res.result.name?.split(' ') || ['', '']
      form.value.first_name = nameParts[0] || ''
      form.value.last_name = nameParts.slice(1).join(' ') || ''
      form.value.address = res.result.address || ''
      form.value.county = res.result.county || 'United States' // Default or from API
      form.value.province = res.result.province || ''
      form.value.city = res.result.city || ''
      form.value.zipcode = res.result.zipcode || ''
      form.value.phone = phoneNumber || ''
      form.value.is_default = res.result.is_default || 0
    }
  }
}

//设置页面标题
uni.setNavigationBarTitle({ title: 'Shipping Address Book' })

//是否默认地址
const isDefaultChange = (event: any) => {
  form.value.is_default = event.detail.value ? 1 : 0
}

//表单实例
const formRef = ref()
//表单规则
const formRules = {
  first_name: {
    rules: [{ required: true, errorMessage: 'Please enter first name' }],
  },
  last_name: {
    rules: [{ required: true, errorMessage: 'Please enter last name' }],
  },
  address: {
    rules: [{ required: true, errorMessage: 'Please enter address' }],
  },
  county: {
    rules: [{ required: true, errorMessage: 'Please select country/region' }],
  },
  province: {
    rules: [{ required: true, errorMessage: 'Please select state/province' }],
  },
  city: {
    rules: [{ required: true, errorMessage: 'Please enter city' }],
  },
  zipcode: {
    rules: [{ required: true, errorMessage: 'Please enter zip/postal code' }],
  },
  phone: {
    rules: [
      { required: true, errorMessage: 'Please enter phone number' },
      // { pattern: /^(\+\d+)\s*(.*)$/, errorMessage: 'Please enter a valid phone number' },
    ],
  },
}

// Close popup and go back
const goBack = () => {
  uni.navigateBack()
}

//保存地址
const saveAddress = async () => {
  try {
    await formRef.value?.validate?.()
  } catch (error) {
    console.log(error)
    return
  }

  // Combine firstName and lastName for the API
  const apiData = {
    id: query.id || null,
    // user_id: memberStore.profile?id,
    name: `${form.value.first_name} ${form.value.last_name}`.trim(),
    first_name: form.value.first_name,
    last_name: form.value.last_name,
    phone: `${phoneCode.value} ${form.value.phone}`,
    province: form.value.province,
    city: form.value.city,
    address: form.value.address,
    zipcode: form.value.zipcode,
    county: form.value.county,
    is_default: form.value.is_default || 0,
    full_location: `${form.value.county} ${form.value.province} ${form.value.city}`.trim()
  }

  apiData.user_id = memberStore.profile?.id;

  if (query.id) {
    const res = await putAddressApi({ ...apiData, id: query.id })
    useAddressStore().selectedAddress = res.result
  } else {
    const res = await postAddressApi(apiData)
    useAddressStore().selectedAddress = res.result
  }
  uni.showToast({ icon: 'success', title: query.id ? 'Updated successfully' : 'Added successfully' })
  setTimeout(() => {
    uni.navigateBack()
  }, 1000)
}

// Add phone data handler
const handlePhoneData = (data: any) => {
  if (data.isValid) {
    form.value.phone = data.data.phoneNumber
    phoneCode.value = data.data.countryCode
  }else{
    uni.showToast({
      icon: 'none',
      title: 'Please enter a valid phone number'
    })
  }
}

const countryList = ref<any[]>([])
onLoad(() => {
  getAreaDataApi().then((res) => {
    localAreaData.value = res.result
    if (res.result && res.result.length > 0) {
      // Extract states for US
      const usData = res.result.find((country: any) => country.name === 'United States')
      if (usData && usData.children) {
        stateData.value = usData.children
      }
    }
  })
  countryList.value = countries.map((country) => {
    return {
      value: country.alpha2,
      label: country.name,
      code: country.countryCallingCodes.map((code) =>
        code.startsWith("+") ? code.slice(1) : code
      )
    }
  })
})


// 地址补全
// 异步获取地址建议
const querySearchAsync = async (queryString) => {
  // if (!queryString || queryString.length < 3) return []
  if (!queryString || queryString.length < 1) return []

  try {
    const { data } = await getGoogleMap({
      page: 1,
      page_size: 10,
      address: queryString
    })

    const predictions = JSON.parse(data).predictions || []
    return predictions.map(pred => ({
      value: pred.description,        // 显示文本
      description: pred.description,  // 完整地址
      place_id: pred.place_id,        // 唯一标识符
      structured_formatting: pred.structured_formatting // 结构化数据
    }))

  } catch (error) {
    console.error('地址请求失败:', error)
    return []
  }
};


// 国家列表
//定义接收用户选择的区号
const phoneCountryCode = ref('us')
const checkPhone = ref(false)
const changeCountry = (value) => {
  form.value.county = value
}

// 地址建议列表
const addressSuggestions = ref<any[]>([])

// 处理地址输入
const handleAddressInput = debounce(async (value: string) => {
  if (value) {
    const suggestions = await querySearchAsync(value)
    addressSuggestions.value = suggestions
  } else {
    addressSuggestions.value = []
  }
}, 300)

// 选择地址建议
const selectAddressSuggestion = (suggestion: any) => {
  form.value.address = suggestion.description
  addressSuggestions.value = []

  // 如果有place_id，可以获取更多地址详情
  if (suggestion.place_id) {
    getAddressDetails(suggestion.place_id)
  }
}

// 辅助方法：获取地址次级信息
const getAddressDetails = async (place_id: string) => {
  const addressParams = {
    page: 1,
    page_size: 10,
    address: form.value.address,
  }
  try {
    const res = await getMapInfo(addressParams);
    if (res.code !== 200) {
      throw new Error(`Failed to fetch address suggestions with code: ${res.code}`);
    }
    if (!Array.isArray(res.data) || res.data.length === 0) {
      return;
    }
    res.data.forEach(item => {
      if (Array.isArray(item.types) && item.types.length > 0) {
        if (item.types.includes('postal_code')) {
          form.value.zipcode = item.long_name;
        } else if (item.types.includes('administrative_area_level_1')) {
          form.value.province = item.long_name;
        } else if (item.types.includes('sublocality_level_1')) {
          form.value.city = item.long_name;
        } else if (item.types.includes('locality')) {
          form.value.city = item.long_name;
        }
      }
    });
  } catch (error) {
    console.error('Error fetching address suggestions:', error);
  }
}


onShowRefreshData(() => {
  getAddressDetail()
})
</script>

<template>
  <view class="page">
    <view class="header">
      <text class="close-icon" @tap="goBack">×</text>
      <text class="title">Shipping Address Book</text>
    </view>

    <uni-forms ref="formRef" :rules="formRules" :model="form" validateTrigger="blur">
      <!-- Name fields -->
      <view class="form-row">
        <uni-forms-item name="first_name" class="form-column">
          <text class="field-label">First name</text>
          <uni-easyinput class="field-input" v-model="form.first_name" placeholder="First name" />
        </uni-forms-item>
        <uni-forms-item name="last_name" class="form-column">
          <text class="field-label">Last name</text>
          <uni-easyinput class="field-input" v-model="form.last_name" placeholder="Last name" />
        </uni-forms-item>
      </view>

      <!-- Address Line -->
      <uni-forms-item name="address" class="form-item">
        <text class="field-label">Address Line 1</text>
        <view class="address-search-container">
          <uni-easyinput class="field-input address-input" placeholder="Street, Apartment, suite, building, floor, etc."
            v-model="form.address" @input="handleAddressInput" />
          <view class="address-suggestions" v-if="addressSuggestions.length > 0">
            <view class="suggestion-item" v-for="(suggestion, index) in addressSuggestions" :key="index"
              @tap="selectAddressSuggestion(suggestion)">
              {{ suggestion.description }}
            </view>
          </view>
        </view>
      </uni-forms-item>
      <!-- <view class="field-hint">Example: Street, Apartment, suite, building, floor, etc. (38 Skillman St, Apt B6)</view> -->
      <view class="field-warning">Note: We're not able to deliver the goods to the Canary Islands, Ceuta and Melilla at
        the moment, sorry for the inconvenience.</view>
      <!-- Country and State -->
      <view class="form-row">
        <uni-forms-item name="county" class="form-column">
          <text class="field-label">Recipient Country</text>
          <view class="field-select">
            <picker mode="selector" :range="countryList" range-key="label" range-value="label"
              @change="(e) => form.county = countryList[e.detail.value].label">
              <view class="uni-input">{{ form.county || 'please select country' }}</view>
            </picker>
          </view>
        </uni-forms-item>
        <uni-forms-item name="province" class="form-column">
          <text class="field-label">State/Province</text>
          <view class="field-select">
            <picker mode="selector" :range="stateOptions" range-key="label"
              @change="(e) => form.province = stateOptions[e.detail.value].value">
              <view class="uni-input">{{ form.province || 'please select province' }}</view>
            </picker>
          </view>
        </uni-forms-item>
      </view>

      <!-- City and Zip -->
      <view class="form-row">
        <uni-forms-item name="city" class="form-column">
          <text class="field-label">City</text>
          <uni-easyinput class="field-input" v-model="form.city" placeholder="City" />
        </uni-forms-item>
        <uni-forms-item name="zipcode" class="form-column">
          <text class="field-label">Zip/Postal Code</text>
          <uni-easyinput class="field-input" type="text" v-model="form.zipcode" placeholder="Zip code" />
        </uni-forms-item>
      </view>

      <!-- Phone Number -->
      <uni-forms-item name="phone" class="form-item">
        <text class="field-label">Phone Number</text>
        <phone-number-input :initialPhoneNumber="form.phone" :initialCountryCode="phoneCode"
          @update:phoneData="handlePhoneData" />
        <!-- <view class="phone-input-container">
          <view class="country-code">
            <picker mode="selector" disabled :value="0" :range="['US +1']">
              <view class="uni-input">US +1</view>
            </picker>
          </view>
          <uni-easyinput class="phone-input" placeholder="Enter phone number" v-model="form.phone" />
        </view> -->
        <!-- <view class="field-warning">Note: May be used to assist delivery</view>
        <view class="phone-info">We ask for your phone number just incase we need to reach you for any reason regarding your order with hlsclothing.net. We do not rent, share, or sell your personal information. Ever.</view> -->
      </uni-forms-item>

      <!-- Default Address -->
      <view class="default-address">
        <switch @change="isDefaultChange" color="#67CCC4" :checked="form.is_default === 1" />
        <text class="default-text">Set as Default</text>
      </view>
    </uni-forms>

    <!-- Submit Button -->
    <view class="operate">
      <button class="submit-btn" @tap="saveAddress">Save</button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
page {
  background-color: #ffffff;
}

.page {
  padding: 0 30rpx;

  .header {
    position: relative;
    padding: 30rpx 0;
    text-align: center;
    border-bottom: 1rpx solid #eee;
    margin-bottom: 30rpx;

    .close-icon {
      position: absolute;
      top: 20rpx;
      right: 10rpx;
      font-size: 38rpx;
      line-height: 60rpx;
      cursor: pointer;
    }

    .title {
      font-size: 26rpx;
      font-weight: 400;
    }
  }

  .form-row {
    display: flex;
    // margin-bottom: 30rpx;

    .form-column {
      flex: 1;
      margin-right: 20rpx;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .form-item {
    margin-bottom: 30rpx;
  }

  .field-label {
    display: block;
    font-size: 24rpx;
    margin-bottom: 16rpx;
    color: #333;
  }

  .field-input {
    width: 100%;
    height: 80rpx;

    :deep(.uni-easyinput__content) {
      background-color: #f7f7f7;
      border: 1rpx solid #ddd !important;
      border-radius: 8rpx;
      padding: 0 20rpx;

      .uni-easyinput__placeholder-class {
        font-size: 24rpx;
      }

      .is-input-border {
        border: none !important;
      }
    }
  }

  .address-input {
    height: 80rpx;
  }

  .field-select {
    width: 100%;
    position: relative;

    .uni-input {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      padding: 0 20rpx;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;
      font-size: 28rpx;
      box-sizing: border-box;
      background-color: #f7f7f7;
      color: #333;
    }
  }

  .phone-input-container {
    // display: flex;

    .country-code {
      width: 180rpx;
      margin-right: 20rpx;

      .uni-input {
        width: 100%;
        height: 80rpx;
        line-height: 80rpx;
        padding: 0 20rpx;
        border: 1rpx solid #ddd;
        border-radius: 8rpx;
        font-size: 28rpx;
        box-sizing: border-box;
        background-color: #f7f7f7;
        color: #333;
      }
    }

    .phone-input {
      flex: 1;
    }
  }

  .field-hint {
    font-size: 24rpx;
    color: #666;
    margin-top: 10rpx;
  }

  .field-warning {
    font-size: 24rpx;
    color: #ff5f3c;
    margin-top: 10rpx;
    margin-bottom: 20rpx;
  }


  .uni-forms-item.is-direction-left {
    width: 100%;
  }

  .phone-info {
    font-size: 24rpx;
    color: #666;
    margin-top: 10rpx;
    line-height: 1.4;
  }

  .default-address {
    display: flex;
    align-items: center;
    margin: 40rpx 0;

    .default-text {
      font-size: 28rpx;
      margin-left: 16rpx;
    }
  }

  .operate {
    padding: 30rpx 0 50rpx;

    .submit-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      border-radius: 90rpx;
      background-color: #ff5f3c;
      color: #ffffff;
      font-size: 32rpx;
      // border-radius: 8rpx;
      text-align: center;
      margin: 0;
    }
  }
}

/* Fix for uni-easyinput component */
:deep(.uni-forms-item__inner) {
  padding-bottom: 0 !important;
}

:deep(.country-selector) {
  width: 28%;
}

:deep(.uni-forms-item__error) {
  padding-top: 8rpx;
  color: #ff5f3c;
}

:deep(.uni-easyinput__content-input) {
  height: 80rpx !important;
}

.address-search-container {
  position: relative;
  width: 100%;
}

.address-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 200px;
  overflow-y: auto;
  background-color: #ffffff;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  z-index: 100;
}

.suggestion-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
  font-size: 14px;
  color: #333;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-item:active {
  background-color: #f9f9f9;
}
</style>
